package com.lvan.excelhandle.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.lvan.excelhandle.bean.StudentExcel;
import com.lvan.excelhandle.listener.ExcelListener;
import com.lvan.excelhandle.mapper.ExcelMapper;
import com.lvan.excelhandle.service.ExcelService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author Lvna
 */
@Service
public class ExcelServiceImpl implements ExcelService {

    @Resource
    private ExcelMapper mapper;

    @Override
    public void getStudent4Excel(MultipartFile file, ExcelService service) throws IOException {

        InputStream inputStream = file.getInputStream();
        EasyExcel.read(inputStream, StudentExcel.class, new ExcelListener(service)).sheet().doRead();
    }

    @Override
    public void exportStudentInfo(HttpServletResponse response) throws IOException {
        /*
        ServletOutputStream outputStream = response.getOutputStream();
        List<StudentExcel> allStudentInfo = mapper.searchAllStudentInfo();
        WriteSheet sheet = new WriteSheet();
        sheet.setSheetName("学生信息");
        ExcelWriter writer = new ExcelWriterBuilder()
                .file(outputStream)
                .head(StudentExcel.class)
                .excelType(ExcelTypeEnum.XLSX)
                .build();
        writer.write(allStudentInfo, sheet);
        response.setHeader("Content-disposition", "attachment;filename=" + new String("学生信息表".getBytes("gb2312"), "ISO8859-1") + ".xlsx");
        writer.finish();
        response.setContentType("multipart/form-data");
        response.setCharacterEncoding("utf-8");
        outputStream.flush();
        */

        List<StudentExcel> student = mapper.searchAllStudentInfo();
        String fileName = URLEncoder.encode("学生信息表", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), StudentExcel.class).sheet("学生信息").doWrite(student);
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
    }

    @Override
    public void addStudentList(List<StudentExcel> list) {
        for (StudentExcel student : list) {
            mapper.addStudent(student);
        }
    }
}
